package cn.dapeng.jdk21;

import java.math.BigDecimal;
import java.util.concurrent.FutureTask;

public class MultiThreadTest {

    public static final Integer LENGTH = 1_0000_0000;

    public static double[] data = new double[LENGTH];

    static {
        for (int i = 0; i < LENGTH; i++) {
            data[i] = Math.random();
        }
    }


    public static void m1() {
        long begin = System.currentTimeMillis();
        double sum = 0;
        for (int i = 0; i < LENGTH; i++) {
            sum += data[i];
        }

        long end = System.currentTimeMillis();
        System.out.println("sum = " + print(sum) + " \t time = " + (end - begin));
    }
    public static void main(String[] args) {

        m1();


        long begin = System.currentTimeMillis();
        int segment = Runtime.getRuntime().availableProcessors();
        FutureTask<Double>[] futureTasks = new FutureTask[segment];

        for (int i = 0; i < segment; i++) {
            int step = i * (LENGTH / segment);
            final int index = i;
            futureTasks[i] = new FutureTask<>(() -> {
                double sum = 0;
                for (int start = step; start < step + (LENGTH / segment); start++) {
                    sum += data[start];
                }
                return sum;
            });

            //Thread.ofVirtual().name("v_3").unstarted(futureTasks[i]).start();
            Thread.ofVirtual().name("v_3").start(futureTasks[i]);
        }

        double sum = 0;
        for (FutureTask<Double> futureTask : futureTasks) {
            try {
                sum += futureTask.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("sum = " + print(sum) + " \t time = " + (end - begin));
    }

    public static String print(double d) {
        BigDecimal v = BigDecimal.valueOf(d);
        return v.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }
}
